import { message } from "ant-design-vue";
import { defineComponent, reactive, ref, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore as useTagsStore } from "@/store/tags";
import ChordsSign from "./ChordsSign/ChordsSign";
import styles from "./index.module.less";
import LyricsSign from "./LyricsSign/LyricsSign";
import ToneSign from "./ToneSign/ToneSign";
import {
  $musicSongDisMelodyAnalysis,
  $musicSongDetail,
} from "@/apis/music/song/song";
import to from "await-to-js";
import eventBus from "@/common/eventBus/mitt";
import pako from "pako";
import uint8Array2Base64 from "@/common/utils/uint8Array2Base64";
import fetchBase64AsUint8Array from "@/common/utils/fetchBase64AsUint8Array";
export default defineComponent({
  name: "DisMelodyAnalysis",
  setup() {
    const route = useRoute();
    const router = useRouter();
    const tagsStore = useTagsStore();
    const LyricsSignRef = ref(null as any);
    const ToneSignRef = ref(null as any);
    const ChordsSignRef = ref(null as any);
    const modify = ref(false);
    const state = ref({
      beat: null as number | null,
      temp: null as number | null,
      value: null,
      score_tone: null,
      chord_tone: 'C',
      arr: [] as any,
      actived: [-1, -1],
      remarks: [] as any[],
    })
    const steps = reactive({
      list: [
        {
          title: '歌词填入',
          content: () => <LyricsSign ref={LyricsSignRef} state={state.value} />,
        },
        {
          title: '调号填入',
          content: () => <ToneSign ref={ToneSignRef} state={state.value} />,
        },
        {
          title: '和弦打谱',
          content: () => <ChordsSign ref={ChordsSignRef} modify={modify.value} state={state.value}
            onSetRemark={(val) => {
              if (state.value.remarks.map(x => x.name).includes(val.choose.name) || !val.choose.name) {
                return;
              }
              state.value.remarks.push({
                name: val.choose.name,
                text: `和弦${val.choose.name}暂未录入`,
              });
            }}
            onRemoveRemark={(name) => {
              const idx = state.value.remarks.findIndex(x => x.name === name);
              idx > -1 && state.value.remarks.splice(idx, 1);
            }}
          />,
        },
      ],
      current: -1,
    })
    const init = () => {
      steps.current = 0;
      state.value.beat = null;
      state.value.temp = null;
      state.value.value = null;
      state.value.score_tone = null;
      state.value.chord_tone = "C";
      state.value.arr = [];
      state.value.actived = [-1, -1];
      state.value.remarks = [];
    }
    const nextStep = async () => {
      if (steps.current === 0) {
        if (!state.value.beat) {
          message.error("请输入曲谱节拍!");
          return;
        }
        if (!state.value.temp) {
          message.error("请输入曲谱速度!");
          return;
        }
        if (!state.value.value) {
          message.error("请输入曲谱歌词!");
          return;
        }
      }
      if (steps.current === 1) {
        if (!state.value.score_tone) {
          message.error("请输入曲谱调号!");
          return;
        }
        if (!state.value.chord_tone) {
          message.error("请输入和弦调号!");
          return;
        }
      }
      steps.current++;
    }
    const prevStep = () => {
      steps.current--;
    }
    const upload = async () => {
      const id = Number(route.query.id);
      const scoreTone = state.value.score_tone || "";
      const chordTone = state.value.chord_tone || "";
      const result = {
        beat: state.value.beat,
        temp: (state.value.temp && state.value.temp > 0) ? Number(((60 / state.value.temp) * 1000000).toFixed(0)) : 0,
        lyrics: state.value.arr.map(x => {
          return x.words;
        })
      }
      const resultStr = JSON.stringify(result);
      let event = encodeURIComponent(resultStr);
      let events_pako = pako.deflate(event);
      let lyricsData: any = await uint8Array2Base64(events_pako);
      const remark = state.value.remarks?.map(x => x.name)?.join(",");
      const [err, res] = await to($musicSongDisMelodyAnalysis({
        id,
        scoreTone,
        chordTone,
        lyricsData,
        remark,
      }))
      if (!err) {
        message.success("打谱成功!");
        init();
        eventBus.analysisFinish.emit();
        tagsStore.removeTagSimple(route.name);
        router.go(-1);
      }
    }
    // 获取详情
    const getDetail = async () => {
      const id: string = String(route.query.id);
      const [err, res]: any = await to($musicSongDetail(id));
      if (!err) {
        try {
          const resultObj = res?.data?.data || null;
          let events_pako_return = "";
          const uint8Arr = await fetchBase64AsUint8Array(resultObj.lyricsData);
          events_pako_return = new TextDecoder().decode(pako.inflate(uint8Arr));
          events_pako_return = decodeURIComponent(events_pako_return);
          const xmlData = JSON.parse(events_pako_return);
          state.value.beat = xmlData.beat ? Number(xmlData.beat) : null;
          state.value.temp = (xmlData.temp && Number(xmlData.temp) > 0) ? Number((60 / (Number(xmlData.temp) / 1000000)).toFixed(0)) : 0;
          state.value.arr = xmlData.lyrics?.map(x => {
            return {
              words: x,
            }
          })
          state.value.score_tone = resultObj.scoreTone || null;
          state.value.chord_tone = resultObj.chordTone || null;
          let remarks: any = [];
          if (resultObj.remark) {
            resultObj.remark?.split?.(",")?.forEach?.(x => {
              remarks.push({
                name: x,
                text: `和弦${x}暂未录入`
              })
            })
          }
          state.value.remarks = remarks;
        } catch (e) { }
      }
    }
    onMounted(async () => {
      init();
      if (route.query?.modify === '1') {
        await getDetail();
        modify.value = true;
        nextTick(() => {
          steps.current = 2;
        })
      } else {
        steps.current = 0;
      }
    })
    return () => (
      <div class={styles.disMelodyAnalysis}>
        <div class={styles['wall-paper']}>
          <div class={styles["steps-diots"]}>
            <a-steps current={steps.current}>
              {
                steps.list.map(item => (
                  <a-step key={item.title} title={item.title} />
                ))
              }
            </a-steps>
          </div>
        </div>
        <div class={styles['steps-content']}>
          {
            steps.list[steps.current]?.content?.()
          }
        </div>
        <div class={styles['steps-btn']}>
          {
            steps.current !== 0 && <a-button disabled={modify.value} onClick={() => { prevStep() }}>上一步</a-button>
          }
          {
            steps.current !== steps.list.length - 1 && <a-button type="primary" onClick={() => { nextStep() }}>下一步</a-button>
          }
          {
            steps.current === steps.list.length - 1 && <a-button type="primary" onClick={() => { upload() }}>上传</a-button>
          }
        </div>
      </div>
    )
  }
})